import uvicorn
import os
import sys
import logging

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.StreamHandler(),
        logging.FileHandler('backend.log', encoding='utf-8')
    ]
)
logger = logging.getLogger("Backend-Startup")

def check_dependencies():
    """检查必要的依赖是否已安装"""
    required_packages = [
        "fastapi", "uvicorn", "pyjwt", "python-multipart", 
        "psutil", "pillow", "pytesseract", "pydantic"
    ]
    
    try:
        import pkg_resources
        
        missing_packages = []
        for package in required_packages:
            try:
                pkg_resources.get_distribution(package)
            except pkg_resources.DistributionNotFound:
                missing_packages.append(package)
        
        if missing_packages:
            logger.warning(f"缺少以下依赖包: {', '.join(missing_packages)}")
            logger.info("正在安装缺失的依赖...")
            
            import subprocess
            subprocess.check_call([
                sys.executable, "-m", "pip", "install", *missing_packages
            ])
            logger.info("依赖安装完成")
    
    except Exception as e:
        logger.error(f"检查依赖时出错: {str(e)}")
        raise

def main():
    """启动后端服务"""
    try:
        # 确保工作目录正确
        script_dir = os.path.dirname(os.path.abspath(__file__))
        os.chdir(script_dir)
        
        logger.info("正在检查依赖...")
        check_dependencies()
        
        logger.info("正在启动后端服务...")
        # 启动FastAPI应用
        uvicorn.run(
            "backend.main:app",
            host="0.0.0.0",
            port=8000,
            reload=True,
            log_level="info"
        )
    
    except Exception as e:
        logger.error(f"启动后端服务时出错: {str(e)}")
        sys.exit(1)

if __name__ == "__main__":
    main() 